﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CERT.Services.DAL;
using System.Configuration;

namespace CERT.Services
{
    public partial class NETServices : CERT.Services.INETServices
    {
        public IEnumerable<Incident> GetAllIncidents()
        {
            using (var context = new NETEntities())
            {
                return context.Incidents.ToList<Incident>().AsEnumerable<Incident>();

            }

        }



        public Incident GetSingleIncident(System.Linq.Expressions.Expression<Func<Incident, bool>> predicate)
        {
            Incident entry = null;

            using (var context = new NETEntities())
            {


                try
                {
                    entry = context.Set<Incident>().Include("Locations").Include("Team").FirstOrDefault<Incident>(predicate);
                }
                catch (Exception ex)
                { }

                return entry;
            }
        }

        public void DeleteIncident(int id)
        {

            //todo ideally, you check and see if this the user's only association.
            //if so, delete them.
            using (var context = new NETEntities())
            {
                var entity = context.Set<Incident>().FirstOrDefault(a => a.Id == id);
                context.Set<Incident>().Remove(entity);
                context.SaveChanges();
            }

        }

        public void UpdateIncident(Incident entity, int incidentId)
        {
            //replace with...
            //http://refactorthis.wordpress.com/2012/12/11/introducing-graphdiff-for-entity-framework-code-first-allowing-automated-updates-of-a-graph-of-detached-entities/#comments

            using (var context = new NETEntities())
            {
               
                var existing = context.Incidents.Find(incidentId);
                context.Entry(existing).CurrentValues.SetValues(entity);

            
                context.SaveChanges();
            }

        }

        public void AddIncident(Incident entity)
        {
            using (var context = new NETEntities())
            {
                if (entity.Team == null)
                {
                    var teamEntity = context.Set<Team>().FirstOrDefault(a => a.Id == entity.Team_Id);
                    teamEntity.Incidents.Add(entity);
                    context.Entry(teamEntity).CurrentValues.SetValues(teamEntity);
                }
                else
                {
                    //var AddLocation = entity.Locations.FirstOrDefault(a => a.Id == 0);
                    context.Set<Incident>().Add(entity);
                }
                context.SaveChanges();

            }
        }
    }
}